<?php

require_once "tfsbox.class.php";
require_once "tfsbox_login_view.class.php";

class TFsBOXLogin extends TFsBOX
	{
		private $registered = false;
		private $email_sent = false;

		function __construct($config_log = null,
							 $shouts_log = null,
							 $ip_log = null,
							 $url_log = null,
							 $wordfilters_log = null,
							 $config_obj = null,
							 $db_obj = null,
							 $sess_obj = null)
			{
				parent::__construct($config_log,
									$shouts_log,
									$ip_log,
									$url_log,
									$wordfilters_log,
									$config_obj,
									$db_obj,
									$sess_obj,
									'TFsBOXLoginView');
			}

		function parsePathInfo()
			{
				if (self::$Session->loggedIn())
					TFsBOX::redirect($_SERVER['SCRIPT_NAME']);

				// C-Panel log in
				if (TFsBOX::pathInfo() == "/tfsbox/login")
				{
					if (isset($_POST['tfsbox_username'])
					 && isset($_POST['tfsbox_password']))
					{
						if (!empty($_POST['tfsbox_username'])
						 && !empty($_POST['tfsbox_password']))
						{
							// Flatfile
							if (!TFsBOX::$Database->databaseMode())
							{
								if (strtolower($_POST['tfsbox_username']) == strtolower(TFsBOX::USERNAME)
								 && $_POST['tfsbox_password'] == TFsBOX::PASSWORD)
								{
									setcookie('tfsbox_username', TFsBOX::USERNAME, mktime(date('H'), date('i'), date('s'), date('m'), date('d') + 1, date('Y')), "/");
									$user_id = gen_salt(TFsBOX::USERNAME);
									$_SESSION['tfsbox_sessid'] = $user_id;
									setcookie('tfsbox_userid', $user_id, mktime(date('H'), date('i'), date('s'), date('m'), date('d') + 1, date('Y')), "/");
									TFsBOX::redirect($_SERVER['SCRIPT_NAME']);
								}

								else
									TFsBOXSession::storeNotice('Username or password is wrong.');
							}

							else if (TFsBOX::$Database->databaseConnection())
							{
								if (preg_match(TFsBOX::NameRegex, $_POST['tfsbox_username']))
								{
									// MySQL
									if (TFsBOX::$Database->databaseMode()
									 == TFsBOXDatabase::MYSQL)
									{
										$password_hash = TFsBOX::passwordHash($_POST['tfsbox_username'],
																			  $_POST['tfsbox_password']);

										$sql = "SELECT `id`, `username`, `verified`, `login_ips` FROM ". TFsBOX_DB_PREFIX ."users "
											  ."WHERE `username` = '". $_POST['tfsbox_username'] ."' AND `password` = '". $password_hash ."' "
											  ."LIMIT 1";
										$result = mysql_query($sql);
										$exists = self::$Database->userExists($_POST['tfsbox_username']);
										if ($result && $exists)
										{
											$result = mysql_fetch_object($result);
											if ($result->verified)
											{
												$result->login_ips = explode("\n", $result->login_ips);
												if (!in_array(self::$Session->ip(), $result->login_ips))
													$result->login_ips[] = self::$Session->ip();

												$rand = TFsBOXSession::randomSessionHash();
												$sql = "UPDATE ". TFsBOX_DB_PREFIX ."users SET "
													  ."`auth_token` = '". $rand . TFsBOXSession::sessionHash(false) ."', "
													  ."`login_ips` = '". implode("\n", $result->login_ips) ."' "
													  ."WHERE `id` = '". $result->id ."'";
												if ($result2 = mysql_query($sql))
												{
													TFsBOXSession::setCookie('tfsbox_userid', $result->id);
													TFsBOXSession::setCookie('tfsbox_username', $result->username);
													TFsBOXSession::setCookie('tfsbox_sessid', $rand);
													TFsBOX::redirect($_SERVER['SCRIPT_NAME']);
												}

												else TFsBOX::$Session->storeError("Failure updating session.");
											}

											else TFsBOX::$Session->storeError("This account has not yet been verified.");
										}

										else
										{
											TFsBOX::$Session->storeError("Username or password is incorrect.");
											if ($exists)
												self::$Database->incrementLoginAttempt($_POST['tfsbox_username']);
										}
									}
								}

								else TFsBOX::$Session->storeError("Invalid username provided.");
							}
						}

						else TFsBOX::$Session->storeError("Both fields must be provided.");
					}
				}

				// Registration
				else if (TFsBOX::pathInfo() == "/tfsbox/login/register")
				{
					if (isset($_POST['tfsbox_username'])
					 && isset($_POST['tfsbox_password'])
					 && isset($_POST['tfsbox_email']))
					{
						if ($this->registered = self::$Database->addUser($_POST['tfsbox_username'],
																		 $_POST['tfsbox_password'],
																		 $_POST['tfsbox_email'],
																		 $_POST['tfsbox_site'],
																		 "'". md5($_POST['tfsbox_email']) ."'"))
						{
							$settings = self::$Database->settings();
							if ($settings["verification_method"] == "email")
								mail($_POST['tfsbox_email'], "TFsBOX Registration Verification",
									 "Thank you for registering to ". TFsBOX::Name ."\n\n"
									."There is one more step for you to follow before you can sign in and start shouting -- verify your account.\n\n"
									."You can do so by visiting this page: ". $settings['shoutbox_path'] ."index.php/tfsbox/login/verify_account?". md5($_POST['tfsbox_email']));
						}
					}
				}

				// Verify account
				else if (TFsBOX::pathInfo() == "/tfsbox/login/verify_account")
				{
					$sql = "SELECT `id` FROM ". TFsBOX_DB_PREFIX ."users "
						  ."WHERE `auth_token` = '". mysql_real_escape_string($_SERVER['QUERY_STRING']) ."' LIMIT 1";
					if ($result = mysql_query($sql))
					{
						$result = mysql_fetch_object($result);
						if (!self::$Database->approveUser($result->id))
							TFsBOXSession::storeError("There was a problem approving your account.");
						else
							TFsBOX::redirect($_SERVER['SCRIPT_NAME']."/tfsbox/login");
					}
				}

				// Forgot username
				else if (TFsBOX::pathInfo() == "/tfsbox/login/forgot_username")
				{
					if ($info = self::$Database->userNameByEmail($_POST['tfsbox_email']))
					{
					}
				}
			}

		function renderLogin()
			{
				TFsBOXAbstractView::renderShoutBoxTitleBar();

				if (self::$Session->hasErrors())
					TFsBOXAbstractView::renderErrors();

				if (self::$Session->hasNotices())
					TFsBOXAbstractView::renderNotices();

				if (self::$Database->databaseMode())
					self::$View->renderMenuBar();

				echo "<div id=\"tfsbox_content\">\n";

				if (TFsBOX::pathInfo() == "/tfsbox/login/register"
				 && self::$Database->databaseMode())
				{
					if (!$this->registered)
						self::$View->renderRegisterForm();
					else
						self::$View->renderRegistrationCompletePage();
				}

				else if (TFsBOX::pathInfo() == "/tfsbox/login/reset_password"
					  && self::$Database->databaseMode())
				{
					if (!$this->email_sent)
						self::$View->renderForgotPasswordForm();
					else
						self::$View->renderEmailSent();
				}

				else if (TFsBOX::pathInfo() == "/tfsbox/login/forgot_username"
					  && self::$Database->databaseMode())
				{
					if (!$this->email_sent)
						self::$View->renderForgotUsernameForm();
					else
						self::$View->renderEmailSent();
				}

				else
					self::$View->renderLoginForm();

				echo "</div>\n";
			}
	}

?>
